package edu.xjtu.jih.signup;

import edu.xjtu.jih.common.Utils;
import edu.xjtu.jih.control.user;
import org.apache.ibatis.session.SqlSession;

public class SignupService {
    public static void addUser(SignUpDto dto) {
        SqlSession sqlSession = Utils.openSession();
        try{
            SignUpDao dao = sqlSession.getMapper(SignUpDao.class);

            int newID = dao.findUserNewID() + 1;
            dto.setU_id(newID);
            try {
                dao.insertUser(dto);
            }catch (Exception e){
                e.printStackTrace();
            }
            //dao.insertUser(dto);
            sqlSession.commit();
        }catch(Exception e){
            sqlSession.rollback();
            throw new RuntimeException("注册失败！", e);
        }finally {
            sqlSession.close();
        }
    }

    public boolean checkExist(SignUpDto dto) {

        SqlSession sqlSession = Utils.openSession();

        try{
            SignUpDao dao = sqlSession.getMapper(SignUpDao.class);
            //System.out.println("1");
            int count = dao.findUserName(dto);
            //System.out.println("2");

            sqlSession.commit();
            //System.out.println("3");

            return count > 0;
        }catch(Exception e){
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally{
            sqlSession.close();
        }
    }

    public user get_userbyid(SignUpDto dto){
        SqlSession sqlSession = Utils.openSession();
        try{
            SignUpDao dao = sqlSession.getMapper(SignUpDao.class);
            user u = dao.findUserbyID(dto);
            sqlSession.commit();
            return  u;
        }catch(Exception e){
            sqlSession.rollback();
            throw new RuntimeException(e);
        }finally{
            sqlSession.close();
        }

    }

}
